﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYLitedbBase;

namespace DSPara
{
    public class Entity_SlotItem : TYLitedbBase.Entity_LiteDB_Base
    {
        public int FromSlot { get; set; }
        public int ToSlot { get; set; }
    }

    public class Entity_SlotPara : TYLitedbBase.Entity_LiteDB_Base
    {
        public string SectionId { get; set; }
        public List<Entity_SlotItem> ListSlotItem { get; set; } = new List<Entity_SlotItem>();
    }

    public class SlotHelper
    {
        public string SectionId { get; set; }
        public List<Entity_SlotItem> ListSlotItem { get; set; }
        private int SlotCount = 0;

        public SlotHelper(string section, int slotCount)
        {
            SectionId = section;
            SlotCount = slotCount;
            ListSlotItem = new List<Entity_SlotItem>();
            for (int i = 0; i < slotCount; i++)
            {
                ListSlotItem.Add(new Entity_SlotItem { FromSlot = i + 1, ToSlot = i + 1 });
            }
        }

        public int GetToSlot(int fromSlot)
        {
            var data = ListSlotItem.FirstOrDefault(x => x.FromSlot == fromSlot);
            if (data != null)
                return data.ToSlot;
            return -1;
        }

        public void Init(Entity_SlotPara listData)
        {
            if (listData == null)
                return;
            for (int i = 0; i < ListSlotItem.Count; i++)
            {
                var data = listData.ListSlotItem.FirstOrDefault(x => x.FromSlot == ListSlotItem[i].FromSlot);
                if (data != null)
                {
                    ListSlotItem[i].ToSlot = data.ToSlot;
                }
            }
        }
    }

    public class SlotDataCreator
    {
        private readonly string dbName;

        /// <summary>
        /// 这个是配置的数据库
        /// </summary>
        /// <param name="_dbName"></param>
        public SlotDataCreator(string _dbName)
        {
            dbName = _dbName;
        }

        public bool Init(SlotHelper offsetPara, ref string error)
        {
            var liteDBHelper = new LiteDB_BaseHelper<Entity_SlotPara>(dbName);
            if (liteDBHelper.Get(x => x.SectionId == offsetPara.SectionId, out Entity_SlotPara listData))
            {
                if (listData == null)
                {
                    error = "无默认槽位信息!!";
                    return false;
                }
                offsetPara.Init(listData);
                return true;
            }
            else
            {
                error = $" 读取槽位信息 异常!section:{offsetPara.SectionId}-本地文件为{LiteDBHelper.GetFileFullPath(dbName)} ";
            }
            return false;
        }
    }
}